Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderItems: [],
    totalAmount: 0,
    deliveryFee: 10,
    cartCount: 0,
    paymentOptions: [
      { id: 'wechat', name: '微信支付', icon: '/images/icon-wechat.png' },
      { id: 'alipay', name: '支付宝', icon: '/images/icon-alipay.png' },
      { id: 'card', name: '银行卡', icon: '/images/icon-bank.png' }
    ],
    selectedPayment: 'wechat',
    orderId: '',
    userId: null // 添加用户ID字段
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取用户ID（假设从全局状态或缓存中获取）
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
      return;
    }

    // 获取临时订单数据
    const tempOrder = wx.getStorageSync('tempOrder') || [];
    if (tempOrder.length === 0) {
      wx.showToast({
        title: '订单数据错误',
        icon: 'none',
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        }
      });
      return;
    }

    // 计算总金额
    const totalAmount = tempOrder.reduce((sum, item) => {
      return sum + (Number(item.price) * item.num);
    }, 0).toFixed(2);

    this.setData({
      orderItems: tempOrder,
      totalAmount: totalAmount,
      cartCount: tempOrder.length,
      userId: userId
    });
  },

  /**
   * 切换支付方式
   */
  onPaymentChange(e) {
    this.setData({
      selectedPayment: e.detail.value
    });
  },

  /**
   * 提交订单
   */
  submitOrder() {
    const { orderItems, totalAmount, selectedPayment, userId } = this.data;
    
    // 生成14位时间戳作为邮编（年月日时分秒）
    const generatePostalCode = () => {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      return `${year}${month}${day}${hours}${minutes}${seconds}`;
    };
    
    // 创建订单对象
    const orderInfo = {
      userId: userId,
      postalCode: generatePostalCode(),
      totalPrice: parseFloat(totalAmount),
      address: wx.getStorageSync('deliveryAddress') || '',
      status: 0 // 0表示购物车状态
    };

    console.log('创建订单数据:', orderInfo);

    // 调用后端API创建订单
    wx.request({
      url: 'http://localhost:8080/orders',
      method: 'POST',
      data: orderInfo,
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        console.log('创建订单响应:', res.data);
        if (res.statusCode === 200) {
          const orderId = res.data.data;
          this.setData({ orderId: orderId });
          
          // 创建订单详情
          const createOrderItems = async () => {
            const { orderItems } = this.data;
            let allSuccess = true;
            let createdItems = []; // 记录已创建的订单项
            
            console.log('订单项数据:', orderItems);
            
            for (const item of orderItems) {
              // 确保数量大于0
              if (!item.num || item.num <= 0) {
                console.error('商品数量无效:', item);
                allSuccess = false;
                break;
              }

              const orderItemData = {
                orderId: orderId,
                productId: parseInt(item.id),
                productCount: parseInt(item.num),
                total: parseFloat(item.price) * parseInt(item.num)
              };
              
              console.log('发送订单项数据:', orderItemData);
              
              try {
                const result = await new Promise((resolve, reject) => {
                  wx.request({
                    url: 'http://localhost:8080/orderitems',
                    method: 'POST',
                    data: orderItemData,
                    header: {
                      'content-type': 'application/json'
                    },
                    success: (res) => {
                      console.log('订单项创建响应:', res);
                      resolve(res);
                    },
                    fail: (err) => {
                      console.error('订单项创建失败:', err);
                      reject(err);
                    }
                  });
                });
                
                if (result.statusCode === 200) {
                  createdItems.push(item);
                } else {
                  console.error('创建订单项失败:', result);
                  allSuccess = false;
                  break;
                }
              } catch (error) {
                console.error('创建订单项出错:', error);
                allSuccess = false;
                break;
              }
            }
            
            if (allSuccess) {
              // 所有订单项创建成功，弹出支付确认框
              wx.showModal({
                title: '确认支付',
                content: `总金额: ¥${totalAmount}`,
                cancelText: '取消支付',
                confirmText: '确认支付',
                success: (res) => {
                  if (res.confirm) {
                    this.processPayment(true, orderId);
                  } else {
                    this.processPayment(false, orderId);
                  }
                }
              });
            } else {
              // 如果有订单项创建失败，删除已创建的订单
              console.log('开始回滚操作，删除订单:', orderId);
              wx.request({
                url: `http://localhost:8080/orders/${orderId}`,
                method: 'DELETE',
                success: (deleteRes) => {
                  console.log('订单删除响应:', deleteRes);
                  if (deleteRes.statusCode === 200) {
                    wx.showToast({
                      title: '创建订单失败',
                      icon: 'none',
                      duration: 2000
                    });
                  } else {
                    console.error('删除订单失败:', deleteRes);
                    wx.showToast({
                      title: '系统错误，请联系客服',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                },
                fail: (error) => {
                  console.error('删除订单失败:', error);
                  wx.showToast({
                    title: '系统错误，请联系客服',
                    icon: 'none',
                    duration: 2000
                  });
                }
              });
            }
          };
          
          createOrderItems();
        } else {
          wx.showToast({
            title: res.data.message || '创建订单失败',
            icon: 'none'
          });
        }
      },
      fail: (error) => {
        console.error('创建订单失败:', error);
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },
  
  /**
   * 处理支付结果
   */
  processPayment(isSuccess, orderId) {
    // 2=已支付待发货，1=待付款，0=已取消（或其他合适的取消状态码）
    const status = isSuccess ? 2 : 1;
    const generatePostalCode = () => Math.floor(100000 + Math.random() * 900000).toString();

    if (isSuccess) {
      // 支付成功，更新订单状态和邮编
      wx.request({
        url: `http://localhost:8080/orders/${orderId}`,
        method: 'PUT',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        data: {
          status: status,
          postalCode: generatePostalCode()
        },
        success: (res) => {
          console.log('更新订单状态响应:', res.data);
          if (res.statusCode === 200) {
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  wx.removeStorageSync('tempOrder');
                  this.setData({
                    orderItems: [],
                    totalAmount: 0,
                    cartCount: 0
                  });
                  wx.redirectTo({
                    url: '/pages/mine/myorder/myorder?tab=3'
                  });
                }, 2000);
              }
            });
          } else {
            wx.showToast({
              title: res.data.message || '更新订单状态失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('更新订单状态失败:', error);
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    } else {
      // 支付失败或取消，只更新状态
      wx.request({
        url: `http://localhost:8080/orders/${orderId}/status?status=${status}`,
        method: 'PUT',
        success: (res) => {
          console.log('更新订单状态响应:', res.data);
          if (res.statusCode === 200) {
            wx.showToast({
              title: '已加入待付款',
              icon: 'none',
              duration: 2000,
              success: () => {
                setTimeout(() => {
                  wx.removeStorageSync('tempOrder');
                  this.setData({
                    orderItems: [],
                    totalAmount: 0,
                    cartCount: 0
                  });
                  wx.redirectTo({
                    url: '/pages/mine/myorder/myorder?tab=2'
                  });
                }, 2000);
              }
            });
          } else {
            wx.showToast({
              title: res.data.message || '更新订单状态失败',
              icon: 'none'
            });
          }
        },
        fail: (error) => {
          console.error('更新订单状态失败:', error);
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
        }
      });
    }
  }
}) 